package com.orange.zkcase4;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * Description: 模拟12306售票案例
 */
public class LockTicket implements Runnable {

    private int tickets = 20;//数据库的票数

    private InterProcessMutex lock;

    public LockTicket() {
        //重试策略，初试时间 3秒，重试3次
        ExponentialBackoffRetry policy = new ExponentialBackoffRetry(3000, 3);
        //通过工厂创建client客户端对象
        CuratorFramework client = CuratorFrameworkFactory
                .builder()
                //zookeeper server列表
                .connectString("192.168.147.128:2181,192.168.147.129:2181,192.168.147.130:2181")
                //connection超时时间
                .connectionTimeoutMs(20000)
                //session超时时间
                .sessionTimeoutMs(20000)
                .retryPolicy(policy)
                .build();
        //启动客户端
        client.start();

        lock = new InterProcessMutex(client, "/locks");
    }

    @Override
    public void run() {
        while (true) {
            try {
                //获取锁
                lock.acquire(3, TimeUnit.SECONDS);
                if (tickets > 0) {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + ":" + tickets);
                    tickets--;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放锁
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
